package com.nhncorp.pleiades.msg;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.nhncorp.pleiades.common.Constants;
import com.nhncorp.pleiades.conf.PleiadesConfiguration;

public class LockValidator implements Validator {

  private ConcurrentHashMap<Integer, String> pathMaps;

  public LockValidator(PleiadesConfiguration conf) {
    pathMaps = new ConcurrentHashMap<Integer, String>();
    pathMaps.put(new Integer(Validator.Mode.LOCK_BASE.ordinal()), conf
        .get("pleiades.lock_base", Constants.LOCK_BASE));
    pathMaps.put(new Integer(Validator.Mode.PERSISTENT_LOCK_BASE.ordinal()), conf
        .get("pleiades.persistent_lock_base", Constants.PERSISTENT_LOCK_BASE));
  }
  
  public boolean isValidate(String path) throws IOException {    
    boolean isValidate = false;
    int index = 0;
    if ((index = path.lastIndexOf("/")) > 0) {
      String dirPath = path.substring(0, index);
      for(Map.Entry<Integer, String> entry : pathMaps.entrySet()) {
        if(entry.getValue().startsWith(path)) {
          throw new IOException("Try to manipulate system default directory :" + path );
        }
        if(dirPath.startsWith(entry.getValue())){
          isValidate = true;
          break;
        }
      }
    }
    return isValidate;
  }

  public boolean isValidate(String path, int mode) throws IOException {
    boolean isValidate = false;
    int index = 0;
    if ((index = path.lastIndexOf("/")) > 0) {
      String dirPath = path.substring(0, index);
      if(pathMaps.get(new Integer(mode)).startsWith(path)) {
        throw new IOException("Try to manipulate system default directory :" + path );
      }
      if(dirPath.startsWith(pathMaps.get(new Integer(mode)))){
        isValidate = true;
      }
    }
    return isValidate;
  }

}
